
/**
 * Upload selected image to temprorary
 * and return file name.
 *
 * jQuery plugin
*/

$.fn.Upload = function(param){
    
    var settings = $.extend({},{
        'success':  null,
        'fail': null,
        'handle':null,
        'form':null,
        'callback':null
    },param);
        
    
        
    if(settings.handle == null || settings.form == null)
    {
        Console.log("Missing handle!");
        return false;
    }
    
    var element = $(this);
    var handle = $((settings.handle));
    var form = $('form[name="'+settings.form+'"]');
            
    var frame = 'iframe-upload';
    
    if(!form){
        Console.log("Missing form handle!");
        return false;
    }
    
    // Actions 
    
    $(this).on("click", function()
    {        
        form.append('<iframe name="'+frame+'" id="'+frame+'" style="display: none"></iframe>');
        handle.click();
        
        
        $('iframe[id='+frame+']').load(function(){
            var data = $(this).contents().find('body');	        
            data = jQuery.parseJSON(data.html());
            
            System.CloseProgressWindow();
            if(!data.result)
            {
                System.WindowTooltip('error',data.message);
            }else{
                if(typeof(settings.callback) == "function")
                {
                    settings.callback(element, data);
                }
            }
            $('#'+frame).remove();
        });
    });
    
    
    
    handle.bind('change',function(){
        img = $(this).val();
        
        // Upload image 
        form.attr({
            'target':frame,
            'action':'/admin/upload'
        });       
        System.ProgressWindow('Trwa wysyłanie zdjęcia');
        form.submit();
    });
    
     
      
};